#include "markdownrender.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sys/stat.h>
#include <direct.h>

using namespace std;

bool createDirectory(const string& path) {
#ifdef _WIN32
    return _mkdir(path.c_str()) == 0;
#else
    return mkdir(path.c_str(), 0755) == 0;
#endif
}

// 独立的文件读取函数，避免与markdownrender.hpp冲突
string readTemplateFile(const string& filename) {
    ifstream file(filename.c_str());
    string content, line;
    if(file.is_open()){
        while(getline(file, line)){
            content += line + "\n";
        }
        file.close();
    } else {
        cerr << "Warning: " << filename << " not found" << endl;
    }
    return content;
}

void init(){
    ofstream fout("list.txt");
    fout.close();
}

void render(string filename){
    string sourcePath = "./source/" + filename + ".md";
    ifstream fin(sourcePath.c_str());
    if(!fin.is_open()){
        cerr << "Error: Cannot open source file: " << sourcePath << endl;
        return;
    }
    
    // 创建输出目录
    string outputDir = "./public/" + filename;
    createDirectory(outputDir);
    
    string outputPath = outputDir + "/index.html";
    ofstream fout(outputPath.c_str());
    if(!fout.is_open()){
        cerr << "Error: Cannot create output file: " << outputPath << endl;
        return;
    }
    
    // 读取模板文件
    string headContent = readTemplateFile("Head.html");
    string footContent = readTemplateFile("Foot.html");
    
    // 写入头部（只写一次）
    fout << headContent;
    
    // 读取并转换Markdown内容
    string MARK, markdownContent;
    while(getline(fin, markdownContent)){
        MARK += markdownContent + "\n";
    }
    fin.close();
    
    string htmlContent = markdownToHtml(MARK);
    fout << htmlContent;
    
    // 写入尾部（只写一次）
    fout << footContent;
    
    fout.close();
    cout << "Rendered: " << filename << " -> " << outputPath << endl;
}

int main(int argc, const char **argv){
    // 确保必要的目录存在
    createDirectory("./source");
    createDirectory("./public");
    createDirectory("./_post");
    
    vector<string> fn;
    
    if(argc == 1){
        init();
        cout << "Initialized list.txt" << endl;
        return 0;
    }
    
    ifstream config("list.txt");
    if(!config.is_open()){
        cerr << "Error: Cannot open list.txt" << endl;
        return 1;
    }
    
    string temp;
    while(config >> temp){
        fn.push_back(temp);
    }
    config.close();
    
    if(argc == 2){
        // 渲染所有文件
        for(size_t i = 0; i < fn.size(); i++){
            render(fn[i]);
        }
        
        // 生成首页
        ofstream fout("./public/index.html");
        if(!fout.is_open()){
            cerr << "Error: Cannot create index.html" << endl;
            return 1;
        }
        
        // 读取模板文件
        string headContent = readTemplateFile("Head.html");
        string footContent = readTemplateFile("Foot.html");
        
        // 写入头部（只写一次）
        fout << headContent;
        
        // 添加页面标题和主要内容
        fout << "<main class=\"main-content\">\n";
        fout << "<div class=\"page-header\">\n<h1 class=\"page-title\">ZEC Blog List</h1>\n<p class=\"page-description\">查看ZEC Blog</p>\n</div>\n";
        
        // 生成博客列表卡片（从最新到最旧）
        for(int i = fn.size() - 1; i >= 0; i--){
            fout << "<div class=\"card\">\n";
            fout << "<div class=\"card-header\">\n";
            fout << "<i class=\"fas fa-users\"></i>\n";
            fout << fn[i];
            fout << "\n</div>\n";
            fout << "<div class=\"card-body\">\n";
            
            string descriptionPath = "./_post/" + fn[i] + ".txt";
            ifstream descFile(descriptionPath.c_str());
            string description, line;
            if(descFile.is_open()){
                while(getline(descFile, line)){
                    if(!description.empty()) description += " ";
                    description += line;
                }
                descFile.close();
            } else {
                description = "No description available";
            }
            
            fout << "<p>" << description << "</p>\n";
            fout << "</div>\n";
            fout << "<div class=\"card-footer\">\n";
            fout << "<button class=\"btn\"><a href=\"./" << fn[i] << "/\">查看详情</a></button>\n";
            fout << "</div>\n</div>\n";
        }
        
        fout << "</main>\n";
        
        // 写入尾部（只写一次）
        fout << footContent;
        
        fout.close();
        cout << "Generated index.html successfully" << endl;
    }
    
    if(argc == 3){
        string Name = argv[2];
        
        // 创建Markdown文件
        string mdPath = "./source/" + Name + ".md";
        ofstream mdFile(mdPath.c_str());
        if(mdFile.is_open()){
            mdFile << "# " << Name << "\n\n欢迎来到我的博客文章！";
            mdFile.close();
            cout << "Created: " << mdPath << endl;
        }
        
        // 创建描述文件
        string descPath = "./_post/" + Name + ".txt";
        ofstream descFile(descPath.c_str());
        if(descFile.is_open()){
            descFile << "这是 " << Name << " 的博客文章描述";
            descFile.close();
            cout << "Created: " << descPath << endl;
        }
        
        // 添加到list.txt
        ofstream listFile("list.txt", ios::app);
        if(listFile.is_open()){
            listFile << Name << endl;
            listFile.close();
            cout << "Added " << Name << " to list.txt" << endl;
        }
    }
    
    return 0;
}